#pragma once
#include <iostream>
#include <string>
#include "Protocol.hpp"

enum
{
    Div_Zero = 1,
    Mod_Zero,
    Other_Oper
};

class Calculator
{
public:
    Calculator()
    {
    }

    ~Calculator()
    {
    }
    Response CalculatorHelper(const Request &req)
    {
        Response resp(0, 0);
        switch (req.op)
        {
        case '+':
            resp.result = req.x + req.y;
            break;
        case '-':
            resp.result = req.x - req.y;
            break;
        case '*':
            resp.result = req.x * req.y;
            break;
        case '/':
        {
            if (req.y == 0)
            {
                resp.code = Div_Zero;
            }
            else
            {
                resp.result = req.x / req.y;
            }
        }
        break;
        case '%':
        {
            if (req.y == 0)
            {
                resp.code = Mod_Zero;
            }
            else
            {
                resp.result = req.x % req.y;
            }
        }
        break;
        default:
            resp.code = Other_Oper;
            break;
        }

        return resp;
    }

    std::string Handler(std::string &package)
    {
        std::string content;
        if (!Decode(package, &content)) // 分离报头和有效载荷："len"\n"10 + 20"\n
            return "";
        // 走到这里就是完整的报文
        Request req;
        if (!req.DeSerialize(content)) // 反序列化，解析有效载荷 "10 + 20" --> x=10 op="+" y=20
            return "";

        content = "";
        Response resp = CalculatorHelper(req); // 执行计算逻辑
        resp.Serialize(&content);              // 序列化计算结果的有效载荷 result=10, code=0
        content = Encode(content);             // 将有效载荷和报头封装成响应报文 "len"\n"30 0"

        return content;
    }
};